package net.atomarrow.render;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.atomarrow.ioc.ActionContext;

public class ActionRender extends Render {

    public static final String ACTION="ACTION";
    public static final String REDIRECT_TYPE="REDIRECT_TYPE";
    public static final String REDIRECT_TYPE_REDIRECT="REDIRECT_TYPE_REDIRECT";
    public static final String REDIRECT_TYPE_CHAIN="REDIRECT_TYPE_CHAIN";
	@Override
	public void render() {
	       ActionContext context = ActionContext.getContext();
	        HttpServletRequest request =context.getRequest();
	        HttpServletResponse response =context.getResponse();
	    String redirectMode = getAttr(REDIRECT_TYPE);
	    String path =getAttr(ACTION);
	    if(redirectMode.equals(REDIRECT_TYPE_REDIRECT)){
            if(!path.startsWith("/")){
                String currentPath = request.getServletPath();
                currentPath=currentPath.replace(context.getAction().getMethodName(), "");
                if(currentPath.endsWith("//")){
                    currentPath=currentPath.substring(0,currentPath.length()-1);
                }
                if(!currentPath.endsWith("/")){
                    currentPath=currentPath+"/";
                }
                if(ActionContext.getContext().getUrlParam(0)!=null){
                    currentPath=currentPath.substring(0,currentPath.length()-1);
                    currentPath=currentPath.substring(0, currentPath.lastIndexOf("/"));
                }
                if(currentPath.endsWith("//")){
                    currentPath=currentPath.substring(0,currentPath.length()-1);
                }
                path=currentPath+path;
            }
	        try {
	            path =request.getContextPath()+path;
                response.sendRedirect(path);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else if(redirectMode.equals(REDIRECT_TYPE_CHAIN)){
            ActionContext.getContext().setNextAction(path);
        }
	}

}
